package dtd.PHS.VND_ExchangeRate.data;

import dtd.PHS.VND_ExchangeRate.utils.ApplicationContext;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;
import dtd.PHS.VND_ExchangeRate.utils.Logger;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class UpdateGoldService extends Service {
	public class UpdateThread extends Thread {

		private boolean forceUpdate;
		
		public UpdateThread() {
			this.forceUpdate = true;
		}
		@Override
		public void run() {
			while ( true ) {
				if ( ! waitForNextUpdate() ) break;
				updateData();
			}
			stopSelf();
		}

		private void updateData() {
			if (Helpers.isConnectedToInternet() ) {
				SJCGoldParser parser = new SJCGoldParser();
				parser.parse();
				SJCItem price = parser.getPrice();
				if ( price == null || price.getUpdateTime() == null ) {
					Logger.logError("Could not parse gold price !");
				} else {
					VNExDatabase.updateGoldPrice(price);
					broadcastUIUpdate();
				}
			}
		}
		private boolean waitForNextUpdate() {
			int sleepTime = 0;
			while ( true ) {
				try {
					Thread.sleep(SLEEP_TIME);
				} catch (InterruptedException e) {
					return false;
				}
				if ( Thread.interrupted() ) return false;
				if ( forceUpdate ) {
					this.forceUpdate = false;
					return true;
				}
				sleepTime += SLEEP_TIME;
				if ( sleepTime >= SJCItem.UPDATE_PERIOD ) return true;
			}
		}
		public void setForceUpdate(boolean b) {
			this.forceUpdate = b;
		}
	}

	public static final long SLEEP_TIME = 300;
	public static final String UPDATE_GOLD_INTENT = "dtd.phs.vnex.broadcast.gold_price";
	private UpdateThread updateThread;


	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Logger.logInfo("Gold service started !");

		updateThread = new UpdateThread();
		updateThread.start();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		updateThread.setForceUpdate(true);
	}



	@Override
	public void onDestroy() {
		updateThread.interrupt();
		super.onDestroy();
	}


	private void broadcastUIUpdate() {
		Intent i = new Intent();
		i.setAction(UPDATE_GOLD_INTENT);
		ApplicationContext.getContext().sendBroadcast(i);	
	}
}
